package d_user_audit

import (
	"fmt"
	"strings"

	"jihe.common/protos/user_server/proto"
	"jihe.common/tool"
)

func (s *Tx) Create(in *proto.UserDUserAudit) (err error) {
	in.Id = fmt.Sprintf("%d", tool.GetSnowflakeId())
	sqlStr := fmt.Sprintf("INSERT INTO %s (id, realname, id_card, phone, addr, introduction, uid)VALUES($1,$2,$3,$4,$5,$6,$7)", s.Name)
	_, err = s.Db.Exec(sqlStr, in.Id, in.Realname, in.IdCard, in.Phone, in.Addr, in.Introduction, in.Uid)
	if err != nil {
		return
	}
	return
}

func (s *Tx) DeleteByUid(uid string) (err error) {
	sqlStr := fmt.Sprintf("delete from %s where uid = $1", s.Name)
	_, err = s.Db.Exec(sqlStr, uid)
	if err != nil {
		return
	}
	return
}

func (s *Model) GetByUids(uids string) (ret []*proto.UserDUserAudit, err error) {
	vals := make([]interface{}, 0)
	args := make([]string, 0)
	for dx, uid := range strings.Split(uids, ",") {
		vals = append(vals, uid)
		args = append(args, fmt.Sprintf("$%d", dx+1))
	}
	sqlStr := fmt.Sprintf("select id, realname, id_card, phone, addr, introduction, uid,status from %s where uid in ("+strings.Join(args, ",")+")", s.Name)
	rows, err := s.Db.Query(sqlStr, vals...)
	if err != nil {
		return
	}
	defer rows.Close()
	for rows.Next() {
		item := &proto.UserDUserAudit{}
		err = rows.Scan(&item.Id, &item.Realname, &item.IdCard, &item.Phone, &item.Addr, &item.Introduction, &item.Uid, &item.Status)
		if err != nil {
			return
		}
		ret = append(ret, item)
	}
	return
}

func (s *Model) UpdateStatusByUid(uid string, status int) (err error) {
	sqlStr := fmt.Sprintf("update %s set status = $1 where uid = $2", s.Name)
	_, err = s.Db.Exec(sqlStr, status, uid)
	if err != nil {
		return
	}
	return
}
